const qiniu = require('qiniu');
const { SECRETKEY, ACCESSKEY, BUCKET, UPLIMITTIME, srcBucket } = require('../config/getconfig.js')
var mac = new qiniu.auth.digest.Mac(ACCESSKEY, SECRETKEY);

module.exports = {
  /* 获取token */
  getQiniuToken() {
    /* mac鉴权对象 */
    /* 上传的选项 */
    var options = {
      scope: BUCKET,

      expires: Number.parseInt(UPLIMITTIME),
      returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);
    if (uploadToken) {
      /* 获取七牛云token成功 */
      code = 1;
      return { code, uploadToken, msg: "获取七牛云token成功", UPLIMITTIME }
    } else {
      code = 0;
      return { code, uploadToken: null, msg: "获取七牛云token失败" }
    }
  },
  /* 修改名字 */
  updataname(oldname, newname, callback) {
    try {
      let config = new qiniu.conf.Config();
      config.zone = qiniu.zone.Zone_z0;
      let bucketManager = new qiniu.rs.BucketManager(mac, config)
      let options = {
        force: true
      }
      bucketManager.move(BUCKET, oldname, BUCKET, newname, options, callback);
    } catch (error) {
      console.log(error);
    }
  },
  /* 删除图片 */
  deleteimg(key, callback) {
    try {
      let config = new qiniu.conf.Config();
      config.zone = qiniu.zone.Zone_z0;
      let bucketManager = new qiniu.rs.BucketManager(mac, config)
      bucketManager.delete(BUCKET, key, callback)
    } catch (error) {
      console.log(error);
    }
  },
  /* 批量删除 */
  deleteList(data,callback) {
    let config = new qiniu.conf.Config();
    config.zone = qiniu.zone.Zone_z0;
    let bucketManager = new qiniu.rs.BucketManager(mac, config)
    let deleteOperations = data.map(item => {
      return qiniu.rs.deleteOp(BUCKET, item)
    })
    bucketManager.batch(deleteOperations,callback);
  }
}